package demo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-10-22
 * Time: 16:48
 */

// 实现一个固定线程个数的线程池

class MyThreadPool{
    BlockingQueue<Runnable> queue = null;

    MyThreadPool(int n){

        // 初始化线程池，创建固定个数的线程
        // 这里使用ArrayBlockingQueue作为任务队列, 容量为1000

        queue = new ArrayBlockingQueue<>(1000);

        // 创建 N 个线程
        for(int i = 0; i < n; i++) {

            Thread t = new Thread(()->{

               try {
                   while (true){
                       Runnable task = queue.take();
                       task.run();
                   }
               }catch (InterruptedException e){
                   e.printStackTrace();
               }
            });

            t.setDaemon(true);//把线程设置为后台线程，方便结束，注意：此方法必须在线程启动之前调用
            t.start();
        }
    }


    public void submit(Runnable task){
        task.run();
    }

}

public class Demo1 {
    public static void main(String[] args) {
        MyThreadPool pool = new MyThreadPool(10);

        // 向线程池提交任务
        for (int i = 0; i < 100; i++) {
            int id = i;
            pool.submit(()->{
                System.out.println(Thread.currentThread().getName() +" "+ "id=" + id);
            });
        }
    }
}
